<?php

namespace app\admin\controller;

use app\admin\controller\CommonController;
use think\Validate;
use think\Db;
use app\util\Utils;
use app\admin\model\Staff;
use app\admin\model\StaffBindStore;
use app\admin\model\Yuyue;
use app\admin\model\StaffCert;
use app\admin\model\StaffRank;
use app\admin\model\ProvCityArea;
use app\admin\model\CtmCollect;
use app\admin\model\StaffFlow;
use app\admin\model\Store;
use app\admin\model\TradingLabel;
use app\admin\model\StaffHobby;
use app\admin\model\ItemClass;
use app\admin\model\StaffTixian;
use app\admin\model\StaffFlowCopy;
use app\admin\model\StaffTime;
use app\admin\model\StaffFlowNew;
use app\admin\model\StaffTeam;
//use app\admin\model\StaffTeamTrading;
use app\admin\model\StaffTeamDetails;
use app\admin\model\StaffTeamStore;
use app\admin\model\StaffTeamLogs;
use app\admin\model\StaffExaltLogs;
use app\admin\model\StaffAssessScore;
use app\util\File;
use app\admin\model\StaffArticles;
use app\admin\model\StaffSubject;
use app\admin\model\StaffEnlist;

class StaffController extends CommonController {
    /*
     * 美容师列表
     * author xfwed 
     * date 2019.09.11
     */

    public function staffList() {
        $status = input('param.status');
        $prov = input('param.prov');
        $city = input('param.city');
        $area = input('param.area');
        $staffName = input('param.staffName');
        $staffPhone = input('param.staffPhone');
        $perPage = input('param.perPage');
        $page = input('param.page');
        $cert_status = input('param.cert_status'); //0全部 1不需要修改证书 2需要修改	
        $staff_rank = input('param.staff_rank'); //美容师级别筛选
        $warning_level = input('param.warning_level');//预警等级-1全部 0正常  1红色预警  2黄色预警
        $start_time = input('param.start_time');
        $end_time = input('param.end_time');
        $qy_wechat = input('param.qy_wechat');//0全部 1是2否创建了企业微信
        $staff_type = input('param.staff_type');//美容师类型 0全部 1品牌连锁店 2服务授权店

        $status = isset($status) ? $status : 0;
        $perPage = isset($perPage) ? $perPage : 10;
        $page = isset($page) ? $page : 1;
        if ($status == 1) {//1待审核2接单中3请假4离职注销5审核失败
            $where['status'] = 0;
        } elseif ($status == 2) {
            $where['status'] = 1;
            $where['is_job'] = 1;
            $where['staff_on'] = 1;
        } elseif ($status == 3) {
            $where['status'] = 1;
            $where['is_job'] = 2;
            $where['staff_on'] = 1;
        } elseif ($status == 4) {
            $where['staff_on'] = 2;
        } elseif ($status == 5) {
            $where['status'] = 2;
        }

        if ($prov) {
            $where['prov'] = $prov;
        }

        if ($city) {
            $where['city'] = $city;
        }

//        if ($area) {
//            $where['area'] = $area;
//        }
        if ($staffName) {
            $where['staff_name'] = ['like', '%' . $staffName . '%'];
        }
        if ($staffPhone) {
            $where['telephone'] = $staffPhone;
        }
        if ($cert_status) {
            $where['cert_status'] = $cert_status;
        }

        if ($staff_rank) {
            $where['staff_rank'] = $staff_rank;
        }
        if(preg_match("/^[0-9][0-9]*$/" ,$warning_level)){
            $where['warning_level'] = $warning_level;
        }
        if($start_time && $end_time){
            $where['add_time'] = ['between',[$start_time,$end_time]];
        }
        if($qy_wechat == 1){
            $where['qy_wechat'] = ['not null',''];
        }elseif ($qy_wechat == 2) {
            $where['qy_wechat'] = ['null',''];
        }
        if($staff_type){
            $where['type'] = $staff_type;
        }
        
        $where['staff_is_creator'] = 0;
        $where = isset($where) ? $where : [];
        $staffList = Staff::where($where)
                ->field('id,staff_name,telephone,cert_img,add_time,status,staff_on,is_job,money,tx_money,staff_rank,interview,warning_level,qy_wechat,type staff_type')
                ->order('id desc')
                ->paginate($perPage);

        foreach ($staffList as $k => $v) {
            if ($v['status'] == 0) {
                $staffList[$k]['status'] = '待审核';
            } elseif ($v['status'] == 1 && $v['is_job'] == 1 && $v['staff_on'] == 1) {
                $staffList[$k]['status'] = '接单中';
            } elseif ($v['staff_on'] == 2) {
                $staffList[$k]['status'] = '离职注销';
            } elseif ($v['status'] == 1 && $v['is_job'] == 2 && $v['staff_on'] == 1) {
                $staffList[$k]['status'] = '请假';
            } elseif ($v['status'] == 2) {
                $staffList[$k]['status'] = '审核未通过';
            }
            $staffList[$k]['storeNum'] = StaffBindStore::where('staff_id', '=', $v['id'])->count();
            $staffList[$k]['oneSerTime'] = Yuyue::where('staff_id', '=', $v['id'])->where('status', 'in', '3,4,7,8')->order('confirm_time asc')->value('confirm_time');
            $staffList[$k]['serNum'] = Yuyue::where('staff_id', '=', $v['id'])->where('status', 'in', '4,7,8')->count();
        }
        return $this->ajaxReturn(0, '查询成功', $staffList);
    }

    /*
     * 美容师级别
     * author xfwed 
     * date 2019.09.11
     */

    public function staffRankList() {
        $staffRankList = StaffRank::where('is_del', '=', 0)->select();
        return $this->ajaxReturn(0, '查询成功', $staffRankList);
    }

    /*
     * 美容师证书
     * author xfwed 
     * date 2019.09.11
     */

    public function staffCertList() {
        $status = input('param.status');
        $perPage = input('param.perPage');
        $page = input('param.page');
        $staff_name = input('param.staff_name'); //美容师姓名
        $idcard_num = input('param.idcard_num'); //身份证号码

        $status = isset($status) ? $status : 0;
        $perPage = isset($perPage) ? $perPage : 10;
        $page = isset($page) ? $page : 1;
        if ($status == 1) {//0全部1绑定了2未绑定
            $where['staff_year'] = ['<>', 0];
        } elseif ($status == 2) {
            $where['staff_year'] = 0;
        }
        if ($staff_name) {
            $where['staff_name'] = ['like', '%' . $staff_name . '%'];
        }

        if ($idcard_num) {
            $where['idcard_num'] = $idcard_num;
        }
        $where = isset($where) ? $where : [];
        $staffCertList = StaffCert::where($where)
                ->field('id,cert_num,staff_rank,staff_name,idcard_num,staff_year,staff_id,bind_time,add_time')
                ->order('id desc')
                ->paginate($perPage);
        foreach ($staffCertList as $k => $v) {
            $staffCertList[$k]['staff_rank'] = StaffRank::where('id', $v['staff_rank'])->value('name');
        }
        return $this->ajaxReturn(0, '查询成功', $staffCertList);
    }

    /*
     * 添加证书
     * author xfwed 
     * date 2019.09.12
     */

    public function addStaffCert() {
        $rule = [
            'staff_rank' => 'require',
            'num' => 'require',
            'first' => 'require',
        ];
        $msg = [
            'staff_rank.require' => '证书级别必须',
            'num.require' => '添加数量必须',
            'first.require' => '省份首字母必须',
        ];
        $all = input('param.');
        $validate = new Validate($rule, $msg);

        if (!$validate->check($all)) {
            $error = $validate->getError();
            return $this->ajaxReturn(1, $error, null);
        }

        $staff_rank = $all['staff_rank'];
        $num = $all['num'];
        $first = strtoupper($all['first']);
        for ($i = 0; $i < $num; $i++) {
            $certRow = StaffCert::order('id desc')->field('num')->find();
            $certnum = $certRow['num'];
            if (empty($certnum)) {
                $certnum = 1;
            } else {
                $certnum = $certnum + 1;
            }
            $data['cert_num'] = StaffCert::makerCertNum($staff_rank, $first, $certnum);
            $data['staff_rank'] = $staff_rank;
            $data['add_time'] = date('Y-m-d H:i:s');
            $data['num'] = $certnum;
            $add = StaffCert::insert($data);
        }
        if ($add) {
            return $this->ajaxReturn(0, '添加成功', null);
        } else {
            return $this->ajaxReturn(3, '添加失败', null);
        }
    }

    /*
     * 证书绑定美容师
     * author xfwed 
     * date 2019.09.12
     */

    public function staffBindCert() {
        $rule = [
            'id' => 'require',
            'staff_name' => 'require',
            'idcard_num' => 'require',
            'staff_year' => 'require',
        ];
        $msg = [
            'id.require' => '证书id必须',
            'staff_name.require' => '美容师姓名必须',
            'idcard_num.require' => '身份证号码必须',
            'staff_year.require' => '工作年限必须',
        ];
        $all = input('param.');
        $validate = new Validate($rule, $msg);

        if (!$validate->check($all)) {
            $error = $validate->getError();
            return $this->ajaxReturn(1, $error, null);
        }

        $id = $all['id'];
        $staffCertRow = StaffCert::where('staff_year', '<>', 0)->where('id', '=', $id)->find();
        if ($staffCertRow) {
            return $this->ajaxReturn(3, '该证书已经被绑定', null);
        }
        $staffCertRow2 = StaffCert::where('idcard_num', '=', $all['idcard_num'])->find();
        if ($staffCertRow2) {
            return $this->ajaxReturn(3, '该身份证已经被绑定', null);
        }
        $data['staff_name'] = $all['staff_name'];
        $data['idcard_num'] = $all['idcard_num'];
        $data['staff_year'] = $all['staff_year'];
        $data['bind_time'] = date('Y-m-d H:i:s');
        $save = StaffCert::where('id', '=', $id)->update($data);
        if ($save) {
            return $this->ajaxReturn(0, '绑定成功', null);
        } else {
            return $this->ajaxReturn(3, '绑定失败', null);
        }
    }

    /*
     * 审核美容师详情
     * author xfwed 
     * date 2019.09.16
     */

    public function auditStaffInfo() {
        $rule = [
            'id' => 'require',
        ];
        $msg = [
            'id.require' => '美容师id必须',
        ];
        $all = input('param.');
        $validate = new Validate($rule, $msg);

        if (!$validate->check($all)) {
            $error = $validate->getError();
            return $this->ajaxReturn(1, $error, null);
        }

        $id = $all['id'];
        $staffRow = Staff::where('id', '=', $id)
                ->field('id,status,staff_name,telephone,staff_sex,idcard1,idcard2,idcard3,idcard_num,cert_img,health_img,city,add_time,why')
                ->find();
//        if ($staffRow['status'] != 0) {
//            return $this->ajaxReturn(3, '该美容师不需要审核', null);
//        }
        $staffRow['city'] = ProvCityArea::cityName($staffRow['city']);
        $staffRow['height'] = '未知';
        $staffRow['weight'] = '未知';
        $staffRow['age'] = '未知';

        return $this->ajaxReturn(0, '查询成功', $staffRow);
    }

    /*
     * 审核美容师
     * author xfwed 
     * date 2019.09.16
     */

    public function auditStaff() {
        $rule = [
            'id' => 'require',
            'status' => 'require',
            'admin_id' => 'require',
        ];
        $msg = [
            'id.require' => '美容师id必须',
            'status.require' => '状态必须',
            'admin_id.require' => '后台管理员id必须',
        ];
        $all = input('param.');
        $validate = new Validate($rule, $msg);

        if (!$validate->check($all)) {
            $error = $validate->getError();
            return $this->ajaxReturn(1, $error, null);
        }

        $id = $all['id'];
        $status = $all['status']; //1是2否审核通过
        $adminId = $all['admin_id'];
        $staffRow = Staff::where('id', '=', $id)->find();
        if ($staffRow['status'] != 0) {
            return $this->ajaxReturn(3, '该美容师不需要审核', null);
        }
        if ($status == 2) {
            if (empty($all['why'])) {
                return $this->ajaxReturn(3, '失败原因必须', null);
            } else {
                $data['status'] = 2;
                $data['why'] = $all['why'];
                $data['admin_id'] = $adminId;
                $result = Staff::where('id', '=', $id)->update($data);
                if ($result) {
                    return $this->ajaxReturn(0, '审核成功', null);
                }
            }
        } else {
            $staffCertRow = StaffCert::where('idcard_num', '=', $staffRow['idcard_num'])
                    ->where('staff_name', '=', $staffRow['staff_name'])
                    ->find();
            if (empty($staffCertRow)) {
                return $this->ajaxReturn(3, '没有查询到证书信息', null);
            }
            if ($staffCertRow['staff_id'] != 0) {
                return $this->ajaxReturn(3, '该证书已经被绑定', null);
            }
            Db::startTrans();
            $data['cert_id'] = $staffCertRow['id'];
            $data['staff_rank'] = $staffCertRow['staff_rank'];
            $data['staff_year'] = $staffCertRow['staff_year'];
            $data['status'] = 1;
            $data['admin_id'] = $adminId;
            $save = Staff::where('id', '=', $id)->update($data);

            $data2['staff_id'] = $id;
            $save2 = StaffCert::where('id', '=', $staffCertRow['id'])->update($data2);

            if ($save && $save2) {
                Db::commit();
                return $this->ajaxReturn(0, '审核成功', null);
            } else {
                Db::rollback();
                return $this->ajaxReturn(3, '审核失败', null);
            }
        }
    }

    /*
     * 美容师详情
     * author xfwed 
     * date 2019.09.16
     */

    public function staffInfo() {
        $rule = [
            'id' => 'require',
        ];
        $msg = [
            'id.require' => '美容师id必须',
        ];
        $all = input('param.');
        $validate = new Validate($rule, $msg);

        if (!$validate->check($all)) {
            $error = $validate->getError();
            return $this->ajaxReturn(1, $error, null);
        }

        $id = $all['id'];
        $staffRow = Staff::where('id', '=', $id)
                ->field('id,staff_photo,staff_rank,staff_name,city,add_time,telephone,staff_sex,idcard1,idcard2,idcard3,idcard_num,cert_img,health_img,staff_year,tx_money,zfb,money,invite_code,from_code,cert_status')
                ->find();
        //查证书编号
        $staffRow['cert_num'] = StaffCert::where('staff_id', $staffRow['id'])->value('cert_num');
        $staffRow['city'] = ProvCityArea::cityName($staffRow['city']);
        $staffRow['height'] = '未知';
        $staffRow['weight'] = '未知';
        $staffRow['age'] = '未知';
        $staffRow['staff_rank'] = StaffRank::rankName($staffRow['staff_rank']);
        //服务人数
        $staffRow['serCtmNum'] = Yuyue::where('staff_id', '=', $id)->where('status', 'in', '4,7,8')->group('ctm_id')->count();
        //服务人次
        $staffRow['serNum'] = Yuyue::where('staff_id', '=', $id)->where('status', 'in', '4,7,8')->count();
        //他的粉丝
        $staffRow['fans'] = CtmCollect::where('type', '=', 2)->where('pro_id', '=', $id)->count();
        //服务营收
        $iteminsert = StaffFlowNew::where('staff_id', '=', $id)->where('type', '=', 1)->where('status', 2)->where('pro_type', 'in', '1,2,3,5')->sum('money');
        $itemrefunt = StaffFlowNew::where('staff_id', '=', $id)->where('type', '=', 2)->sum('money');
        $staffRow['itemMoney'] = $iteminsert - $itemrefunt;
        //商品营收
        $staffRow['goodsMoney'] = StaffFlowNew::where('staff_id', '=', $id)->where('type', '=', 1)->where('status', 2)->where('pro_type', 'in', '6,7')->sum('money');
        //待提现金额
//        $time = time()- 7*24*60*60;
//        $staffRow['noIncome'] = StaffFlowCopy::where('add_time', '>', date('Y-m-d H:i:s',$time))
//                ->where('type', 1)
//                ->where('staff_id', '=', $id)
//                ->sum('money'); 
        $noIncome1 = StaffFlowNew::where('type', 1)
                ->where('status', 'in', '0,1')
                ->where('pro_type', 'in', '1,2,3,4,5,6,7')
                ->where('staff_id', '=', $id)
                ->sum('money');
        $noIncome2 = 0;
        $staffRow['noIncome'] = $noIncome1 - $noIncome2;
        //所在商圈
        $storeIds = StaffBindStore::where('staff_id', '=', $id)->column('store_id');
        $tradingIds = Store::where('id', 'in', $storeIds)->column('store_trading');
        $tradingName = TradingLabel::where('id', 'in', $tradingIds)->column('name');
        $staffRow['trading'] = $tradingName;
        //擅长标签
        $ortherIds = StaffHobby::where('staff_id', '=', $id)->where('type', '=', 1)->column('orther_id');
        $itemClassName = ItemClass::where('id', 'in', $ortherIds)->column('name');
        $staffRow['staffHobby'] = $itemClassName;
        //上次提现时间
        $tixianRow = StaffTixian::where('staff_id', '=', $id)->order('ctime desc')->find();
        $staffRow['lastTixianTime'] = $tixianRow['ctime'];
        //本月营收
        $begin_time = date("Y-m-d H:i:s", mktime(0, 0, 0, date("m"), 1, date("Y")));
        $end_time = date("Y-m-d H:i:s", mktime(23, 59, 59, date("m"), date("t"), date("Y")));
        $staffRow['monthMoney'] = StaffFlowNew::where('staff_id', '=', $id)
                ->where('type', '=', 1)
                ->where('status', 2)
                ->where('add_time', 'between', [$begin_time, $end_time])
                ->sum('money');
        //提现列表
        $staffRow['tixianList'] = StaffTixian::where('staff_id', '=', $id)
                ->field('id,money,poundage,ali_id,ali_name,batch,status,ctime,utime')
                ->select();

        return $this->ajaxReturn(0, '查询成功', $staffRow);
    }

    /*
     * 美容师离职
     * author xfwed 
     * date 2019.11.20
     */

    public function staffLeaveOffice() {
        $rule = [
            'id' => 'require',
        ];
        $msg = [
            'id.require' => '美容师id必须',
        ];
        $all = input('param.');
        $validate = new Validate($rule, $msg);

        if (!$validate->check($all)) {
            $error = $validate->getError();
            return $this->ajaxReturn(1, $error, null);
        }

        $id = $all['id'];
        $staffRow = Staff::where('id', '=', $id)->find();

        if ($staffRow['staff_on'] == 2) {
            return $this->ajaxReturn(3, '该美容师已经离职', null);
        }

        $data['staff_on'] = 2;
        $data['is_job'] = 2;
        $result = Staff::where('id', '=', $id)->update($data);
        if ($result) {
            return $this->ajaxReturn(0, '离职成功', null);
        } else {
            return $this->ajaxReturn(3, '离职失败', null);
        }
    }

    /*
     * 美容师绑定店铺列表
     * author xfwed
     * date 2019.12.19
     */

    public function staffBindStoreList() {
        $staff_id = input('param.staff_id');
        $perPage = input('param.perPage');
        $page = input('param.page');

        $perPage = isset($perPage) ? $perPage : 10;
        $page = isset($page) ? $page : 1;
        $list = StaffBindStore::alias('b')
                ->join('store s', 'b.store_id = s.id', 'left')
                ->join('prov_city_area p', 'p.id = s.city', 'left')
                ->field('b.id,s.id store_id,s.store_name,s.store_keeper,s.keeper_phone,s.logoimg,s.city,s.is_del,s.add_time,p.name')
                ->where('b.staff_id', $staff_id)
                ->paginate($perPage);
        return $this->ajaxReturn(0, '查询成功', $list);
    }

    /*
     * 美容师考勤
     * author xfwed 
     * date 2020.07.06
     */

    public function staffTime() {
        $staff_id = input('param.staff_id');
        $perPage = input('param.perPage');
        $page = input('param.page');

        $status = isset($status) ? $status : 0;
        $perPage = isset($perPage) ? $perPage : 10;
        $page = isset($page) ? $page : 1;
        $staffList1 = StaffTime::where('staff_id', $staff_id)
                ->where('type', 1)
                ->order('id desc')
                ->find();
        $staffList2 = StaffTime::where('staff_id', $staff_id)
                ->where('type', 2)
                ->order('id desc')
                ->paginate($perPage);
        $data['staffList1'] = $staffList1;
        $data['staffList2'] = $staffList2;
        return $this->ajaxReturn(0, '查询成功', $data);
    }

    /*
     * 团队列表
     * author xfwed
     * date 2021.1.12
     */

    public function staffTeamList() {
        $team_name = input('param.team_name'); //团队名
//        $trading_id = input('param.trading_id');//商圈id
        $district_name = input('param.district_name'); //区长名
        $perPage = input('param.perPage');
        $page = input('param.page');

        $perPage = isset($perPage) ? $perPage : 10;
        $page = isset($page) ? $page : 1;

        if ($team_name) {
            $where['si.team_name'] = ['like', '%' . $team_name . '%'];
        }
//        if($trading_id){
//            $where['stt.trading_id'] = $trading_id;
//            $where['stt.is_del'] = 1;
//        }
        if ($district_name) {
            $where['si.district_name'] = ['like', '%' . $district_name . '%'];
        }

        $where = isset($where) ? $where : [];
        $list = StaffTeam::alias('si')
                //->join('staff_team_trading stt','stt.team_id = si.id','left')
                ->field('si.*')
                ->where($where)
                ->paginate($perPage);
//        foreach ($list as $k => $v){
//            $team_id = $v['id'];
//            $tradingName=StaffTeamTrading::where('team_id',$team_id)->column('trading_name');
//            $tradingName = implode(',', $tradingName);
//            $list[$k]['tradingName'] = $tradingName;
//        }
        return $this->ajaxReturn(0, '查询成功', $list);
    }

    /*
     * 添加团队
     * author xfwed 
     * date 2021.01.12
     */

    public function addstaffTeam() {
        $rule = [
            'team_name' => 'require',
            'min_members_num' => 'require',
            'max_members_num' => 'require',
            'base_days' => 'require',
            'base_service_num' => 'require',
            'team_img' => 'require',
        ];
        $msg = [
            'team_name.require' => '团队名称必须',
            'min_members_num.require' => '最少成员数量必须',
            'max_members_num.require' => '最大成员数量必须',
            'base_days.require' => '基础出勤天数必须',
            'base_service_num.require' => '基础接单数必须',
            'team_img.require' => '团队头像必须',
        ];
        $all = input('post.');
        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();
            return $this->ajaxReturn(1, $error, null);
        }
        $captain_id = input('param.captain_id');
        $captain_name = input('param.captain_name');
        $district_id = input('param.district_id');
        $district_name = input('param.district_name');
        $store_ids = input('store_ids');
//        $trading = input('param.trading');
//        $trading = json_decode($trading,true);
        $p = Store::where('id','in',$store_ids)->where('type',1)->find();
        $s = Store::where('id','in',$store_ids)->where('type',2)->find();
        if($p && $s){
             return $this->ajaxReturn(3, '不能同时选择俩种类型的店铺', null);
        }

        Db::startTrans();
        //添加团队基本信息
        $data['team_name'] = $all['team_name'];
        $data['captain_id'] = $captain_id;
        $data['captain_name'] = $captain_name;
        $data['district_id'] = $district_id;
        $data['district_name'] = $district_name;
        $data['min_members_num'] = $all['min_members_num'];
        $data['max_members_num'] = $all['max_members_num'];
        $data['base_days'] = $all['base_days'];
        $data['base_service_num'] = $all['base_service_num'];
        $data['team_img'] = $all['team_img'];
        $data['add_time'] = date('Y-m-d H:i:s');
        $add = StaffTeam::insertGetId($data);
//        //添加团队商圈信息
//        $trading_arr = [];
//        foreach ($trading as $k => $v) {
//            $trading_arr[] = [
//                'team_id' => $add,
//                'trading_id' => $v['id'],
//                'trading_name' => $v['name'],
//                'add_time' => date('Y-m-d H:i:s'),
//            ];
//        }
//        $tradingResult = StaffTeamTrading::insertAll($trading_arr);
        //添加团队店铺信息
        if ($store_ids) {
            $store_ids = explode(',', $store_ids);
            $store_arr = [];
            for ($i = 0; $i < count($store_ids); $i++) {
                $store_arr[] = [
                    'team_id' => $add,
                    'store_id' => $store_ids[$i],
                    'add_time' => date('Y-m-d H:i:s'),
                ];
            }
            $storeIdResult = StaffTeamStore::insertAll($store_arr);
        } else {
            $storeIdResult = true;
        }

        //修改队长的级别
        if ($captain_id) {
            $captainRank = Staff::where('id', $captain_id)->value('staff_rank');
            if ($captainRank != 5) {
                $saveCaptainRank = Staff::saveStaffRank($captain_id, 5);
            } else {
                $saveCaptainRank = true;
            }
        } else {
            $saveCaptainRank = true;
        }

        //修改区长的级别
        if ($district_id) {
            $districtRank = Staff::where('id', $district_id)->value('staff_rank');
            if ($districtRank != 6) {
                $savedistrictRank = Staff::saveStaffRank($district_id, 6);
            } else {
                $savedistrictRank = true;
            }
        } else {
            $savedistrictRank = true;
        }

//        print_r($add.'======'.$storeIdResult.'======'.$saveCaptainRank.'======'.$savedistrictRank);
        if ($add && $storeIdResult && $saveCaptainRank && $savedistrictRank) {
            Db::commit();
            $file = new File();
            $qrcode = $file->generateStaffTeamQrcode($add);
            StaffTeam::where('id', $add)->update(['qrcode' => $qrcode]);
            return $this->ajaxReturn(0, '添加成功', null);
        } else {
            Db::rollback();
            return $this->ajaxReturn(3, '添加失败', null);
        }
    }

    /*
     * 修改团队
     * author xfwed 
     * date 2021.01.13
     */

    public function saveStaffTeam() {
        $requestType = input('param.requestType');
        $id = input('param.id');
        if ($requestType == 1) {//1修改前获取信息 2提交修改
            $teamInfo = StaffTeam::where('id', $id)->find();
            //团队商圈信息
//            $tradingList = StaffTeamTrading::where('team_id',$teamInfo['id'])->where('is_del',1)->select();
//            $teamInfo['tradingList'] = $tradingList;
            //店铺信息
            $storeList = StaffTeamStore::alias('sts')
                    ->join('store s', 's.id = sts.store_id', 'left')
                    ->where('sts.team_id', $teamInfo['id'])
                    ->where('sts.status', 1)
                    //->field('sts.*,s.store_name')
                    ->column('s.id');
            $teamInfo['store_ids'] = $storeList;
            return $this->ajaxReturn(0, '查询成功', $teamInfo);
        } else {
            $rule = [
                'team_name' => 'require',
                'min_members_num' => 'require',
                'max_members_num' => 'require',
                'base_days' => 'require',
                'base_service_num' => 'require',
            ];
            $msg = [
                'team_name.require' => '团队名称必须',
                'min_members_num.require' => '最少成员数量必须',
                'max_members_num.require' => '最大成员数量必须',
                'base_days.require' => '基础出勤天数必须',
                'base_service_num.require' => '基础接单数必须',
            ];
            $all = input('post.');
            $validate = new Validate($rule, $msg);
            if (!$validate->check($all)) {
                $error = $validate->getError();
                return $this->ajaxReturn(1, $error, null);
            }
            $captain_id = input('param.captain_id');
            $captain_name = input('param.captain_name');
            $district_id = input('param.district_id');
            $district_name = input('param.district_name');
            $store_ids = input('store_ids');
//            $trading = input('param.trading');
//            $trading = json_decode($trading,true);

            $teamInfo = StaffTeam::where('id', $id)->find();

            Db::startTrans();
            //添加团队基本信息
            $data['team_name'] = $all['team_name'];
            $data['captain_id'] = $captain_id;
            $data['captain_name'] = $captain_name;
            $data['district_id'] = $district_id;
            $data['district_name'] = $district_name;
            $data['min_members_num'] = $all['min_members_num'];
            $data['max_members_num'] = $all['max_members_num'];
            $data['base_days'] = $all['base_days'];
            $data['base_service_num'] = $all['base_service_num'];
            $data['update_time'] = date('Y-m-d H:i:s');
            $save = StaffTeam::where('id', $id)->update($data);

            //修改团队商圈信息
            //[{"id":1,"name":"\u4e09\u91cc\u5c6f\/\u5de5\u4f53\/\u4e1c\u76f4\u95e8\u5730\u533a"},{"id":2,"name":"\u4ea6\u5e84\u5730\u533a"}]
//            $trading_arr = [];
//            foreach ($trading as $k => $v) {
//                $trading_arr[] = [
//                    'team_id' => $id,
//                    'trading_id' => $v['id'],
//                    'trading_name' => $v['name'],
//                    'add_time' => date('Y-m-d H:i:s'),
//                ];
//            }
//            $saveTrading = StaffTeamTrading::where('team_id',$id)->update(['is_del'=>2]);
//            $tradingResult = StaffTeamTrading::insertAll($trading_arr);
            //添加团队店铺信息
            //解除店与美容师的关系
            if ($store_ids) {
                //当前团队的美容师
                $staffIds = StaffTeamDetails::where('team_id', $id)->where('status', 'in', '1,2')->column('staff_id');
                //删除现有的绑定关系
                if ($staffIds) {
                    $delStaffBindStore = StaffBindStore::where('staff_id', 'in', $staffIds)->delete();
                } else {
                    $delStaffBindStore = true;
                }
                $store_ids = explode(',', $store_ids);
                $store_arr = [];
                $staffbind_arr = [];
                for ($i = 0; $i < count($store_ids); $i++) {
                    $store_arr[] = [
                        'team_id' => $id,
                        'store_id' => $store_ids[$i],
                        'add_time' => date('Y-m-d H:i:s'),
                    ];
                    for ($j = 0; $j < count($staffIds); $j++) {
                        $staffbind_arr[] = [
                            'staff_id' => $staffIds[$j],
                            'store_id' => $store_ids[$i],
                            'add_time' => date('Y-m-d H:i:s'),
                        ];
                    }
                }
                $saveStoreId = StaffTeamStore::where('team_id', $id)->update(['status' => 2]);
                $storeIdResult = StaffTeamStore::insertAll($store_arr);
                if ($staffbind_arr) {
                    $insertStaffBindStore = StaffBindStore::insertAll($staffbind_arr);
                } else {
                    $insertStaffBindStore = true;
                }
            } else {
                $storeIdResult = true;
                $insertStaffBindStore = true;
                $delStaffBindStore = true;
                $saveStoreId = true;
            }
            if ($captain_id != $teamInfo['captain_id']) {//队长修改了
//                //修改旧队长的级别  降级到 金牌美容师3
//                $captainRank = Staff::where('id',$teamInfo['captain_id'])->value('staff_rank');
//                if($captainRank > 3){
//                    $saveCaptainRank = Staff::saveStaffRank($teamInfo['captain_id'], 3);
//                }  else {
//                    $saveCaptainRank = true;
//                }
                $saveCaptainRank = true;
                //修改新队长的级别  升级到 队长5
                $newcaptainRank = Staff::where('id', $captain_id)->value('staff_rank');
                if ($newcaptainRank < 5) {
                    $newsaveCaptainRank = Staff::saveStaffRank($captain_id, 5);
                } else {
                    $newsaveCaptainRank = true;
                }
            } else {
                $saveCaptainRank = true;
                $newsaveCaptainRank = true;
            }

            if ($district_id != $teamInfo['district_id']) {//区长修改了
//                //修改旧区长的级别 降级到 代队长4
//                $districtRank = Staff::where('id',$teamInfo['district_id'])->value('staff_rank');
//                if($districtRank > 4){
//                    $savedistrictRank = Staff::saveStaffRank($teamInfo['district_id'], 4);
//                }  else {
//                    $savedistrictRank = true;
//                }
                $savedistrictRank = true;
                //修改新区长的级别  升级到 区长6
                $newdistrictRank = Staff::where('id', $district_id)->value('staff_rank');
                if ($newdistrictRank < 6) {
                    $newsavedistrictRank = Staff::saveStaffRank($district_id, 6);
                } else {
                    $newsavedistrictRank = true;
                }
            } else {
                $savedistrictRank = true;
                $newsavedistrictRank = true;
            }

            //print_r($save.'---'.$saveStoreId.'---'.$storeIdResult.'---'.$saveCaptainRank.'---'.$newsaveCaptainRank.'---'.$savedistrictRank.'---'.$newsavedistrictRank.'---'.$insertStaffBindStore.'---'.$delStaffBindStore);
            if ($save && $saveStoreId && $storeIdResult && $saveCaptainRank && $newsaveCaptainRank && $savedistrictRank && $newsavedistrictRank && $insertStaffBindStore && $delStaffBindStore) {
                Db::commit();
                return $this->ajaxReturn(0, '修改成功', null);
            } else {
                Db::rollback();
                return $this->ajaxReturn(3, '修改失败', null);
            }
        }
    }

    /*
     * 团队成员列表
     * author xfwed
     * date 2021.1.13
     */

    public function teamStaffList() {
        $status = input('param.status'); //1.在团 2.申请退出 3.退出	
        $team_id = input('param.team_id'); //团队id
        $staff_phone = input('param.staff_phone'); //美容师手机号
        $perPage = input('param.perPage');
        $page = input('param.page');

        $perPage = isset($perPage) ? $perPage : 10;
        $page = isset($page) ? $page : 1;

        if ($status) {
            $where['std.status'] = $status;
        }
        if ($team_id) {
            $where['std.team_id'] = $team_id;
        }
        if ($staff_phone) {
            $where['s.telephone'] = $staff_phone;
        }
        $where = isset($where) ? $where : [];
        $list = StaffTeamDetails::alias('std')
                ->join('staff s', 's.id = std.staff_id', 'left')
                ->join('staff_team st', 'st.id = std.team_id', 'left')
                ->field('std.*,s.staff_name,s.nickname,s.telephone,s.cert_img,st.team_name')
                ->where($where)
                ->paginate($perPage);
        return $this->ajaxReturn(0, '查询成功', $list);
    }

    /*
     * 添加团队成员
     * author xfwed 
     * date 2021.01.13
     */

    public function addteamStaff() {
        $rule = [
            'team_id' => 'require',
            'staff_id' => 'require',
            'admin_name' => 'require',
        ];
        $msg = [
            'team_id.require' => '团队id必须',
            'staff_id.require' => '美容师id必须',
            'admin_name.require' => '后台管理员名称必须',
        ];
        $all = input('post.');
        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();
            return $this->ajaxReturn(1, $error, null);
        }
        $team_id = input('param.team_id');
        $staff_id = input('param.staff_id');
        $admin_name = $all['admin_name'];

        $teamRow = Db::name('staff_team')->where('id', $team_id)->where('status', 1)->find();
        $staffRow = Db::name('staff')->where('id', $staff_id)->find();

        $std = StaffTeamDetails::where('staff_id', $staff_id)
                ->where('status', 'in', '1,2')
                ->find();
        if ($std) {
            return $this->ajaxReturn(3, '该美容师已经绑定团队', null);
        }
        if ($staffRow['staff_rank'] == 5 && $teamRow['captain_id'] != $staff_id) {
            return $this->ajaxReturn(3, '请扫描本团队二维码', null);
        }

        $max_members_num = StaffTeam::where('id', $team_id)->value('max_members_num');
        $stdCount = StaffTeamDetails::where('team_id', $team_id)
                ->where('status', 'in', '1,2')
                ->count();
        if ($stdCount >= $max_members_num) {
            return $this->ajaxReturn(3, '该团队已经满了', null);
        }

        Db::startTrans();
        $std3 = StaffTeamDetails::where('staff_id', $staff_id)
                ->where('status', 3)
                ->find();
        if ($std3) {
            $add = StaffTeamDetails::where('id', $std3['id'])
                    ->update([
                'team_id' => $all['team_id'],
                'staff_id' => $all['staff_id'],
                'status' => 1,
                'add_time' => date('Y-m-d H:i:s')]);
        } else {
            //添加成员
            $data['team_id'] = $all['team_id'];
            $data['staff_id'] = $all['staff_id'];
            $data['add_time'] = date('Y-m-d H:i:s');
            $add = StaffTeamDetails::insertGetId($data);
        }
        //添加团队成员进出记录
        $logsdata['staff_id'] = $all['staff_id'];
        $logsdata['team_id'] = $all['team_id'];
        $logsdata['status'] = 1;
        $logsdata['note'] = '后台管理员' . $admin_name . '添加';
        $logsdata['add_time'] = date('Y-m-d H:i:s');
        $lodsResult = StaffTeamLogs::insert($logsdata);
        //美容师和店铺的绑定关系
        $storeIds = StaffTeamStore::where('team_id', $all['team_id'])
                ->where('status', 1)
                ->column('store_id');
        $staffbind_arr = [];
        for ($j = 0; $j < count($storeIds); $j++) {
            $staffbind_arr[] = [
                'staff_id' => $all['staff_id'],
                'store_id' => $storeIds[$j],
                'add_time' => date('Y-m-d H:i:s'),
            ];
        }
        $sbsResult = StaffBindStore::insertAll($staffbind_arr);

        if ($add && $lodsResult && $sbsResult) {
            Db::commit();
            return $this->ajaxReturn(0, '添加成功', null);
        } else {
            Db::rollback();
            return $this->ajaxReturn(3, '添加失败', null);
        }
    }

    /*
     * 团队成员退出
     * author xfwed 
     * date 2021.01.14
     */

    public function delTeamStaff() {
        $rule = [
            'id' => 'require',
            'status' => 'require',
            'admin_name' => 'require',
        ];
        $msg = [
            'team_id.require' => '团队成员id必须',
            'staff_id.require' => '状态必须',
            'admin_name.require' => '后台管理员名称必须',
        ];
        $all = input('post.');
        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();
            return $this->ajaxReturn(1, $error, null);
        }
        $id = input('param.id');
        $status = input('param.status'); //1拒绝退出3同意退出
        $admin_name = $all['admin_name'];
        $why = input('param.why'); //拒绝原因

        if ($status == 1 && empty($why)) {
            return $this->ajaxReturn(3, '拒绝原因必须', null);
        }

        $std = StaffTeamDetails::where('id', $id)->find();
        if ($std['status'] != 2) {
            return $this->ajaxReturn(3, '该美容师没有申请退团', null);
        }

        Db::startTrans();
        //修改团队成员状态
        $data['status'] = $status;
        $data['audit_name'] = $admin_name;
        $data['audit_time'] = date('Y-m-d H:i:s');
        $data['why'] = $why;
        $add = StaffTeamDetails::where('id', $id)->update($data);
        //团队成员进出记录
        $logsdata['staff_id'] = $std['staff_id'];
        $logsdata['team_id'] = $std['team_id'];
        if ($status == 1) {
            $logstatus = 4;
        } elseif ($status == 3) {
            $logstatus = 3;
        }
        $logsdata['status'] = $logstatus;
        $logsdata['note'] = '后台管理员' . $admin_name . '审核完成';
        $logsdata['add_time'] = date('Y-m-d H:i:s');
        $lodsResult = StaffTeamLogs::insert($logsdata);
        //美容师和店铺的绑定关系
        if ($status == 3) {
            $storeIds = StaffTeamStore::where('team_id', $std['team_id'])
                    ->where('status', 1)
                    ->column('store_id');
            $sbsResult = StaffBindStore::where('staff_id', $std['staff_id'])
                    ->where('store_id', 'in', $storeIds)
                    ->delete();
        } else {
            $sbsResult = true;
        }


        if ($add && $lodsResult && $sbsResult) {
            Db::commit();
            return $this->ajaxReturn(0, '审核成功', null);
        } else {
            Db::rollback();
            return $this->ajaxReturn(3, '审核失败', null);
        }
    }

    /*
     * 团队成员流动列表
     * author xfwed
     * date 2021.1.14
     */

    public function teamStaffTurnoverList() {
        $staff_phone = input('param.staff_phone'); //美容师手机号
        $team_id = input('param.team_id'); //团队id
        $perPage = input('param.perPage');
        $page = input('param.page');

        $perPage = isset($perPage) ? $perPage : 10;
        $page = isset($page) ? $page : 1;

        if ($staff_phone) {
            $where['s.telephone'] = $staff_phone;
        }
        if ($team_id) {
            $where['stl.team_id'] = $team_id;
        }
        $where = isset($where) ? $where : [];
        $list = StaffTeamLogs::alias('stl')
                ->join('staff s', 's.id = stl.staff_id', 'left')
                ->join('staff_team st', 'st.id = stl.team_id', 'left')
                ->field('stl.*,s.staff_name,s.nickname,s.telephone,s.cert_img,st.team_name')
                ->where($where)
                ->paginate($perPage);
        return $this->ajaxReturn(0, '查询成功', $list);
    }

    /*
     * 店铺绑定的团列表
     * author xfwed
     * date 2021.1.14
     */

    public function storeTeamList() {
        $store_id = input('param.store_id'); //店铺id
        $perPage = input('param.perPage');
        $page = input('param.page');

        $perPage = isset($perPage) ? $perPage : 10;
        $page = isset($page) ? $page : 1;

        $where['sts.store_id'] = $store_id;
        $list = StaffTeamStore::alias('sts')
                ->join('staff_team st', 'st.id = sts.team_id', 'left')
                ->field('sts.*,st.team_name')
                ->where($where)
                ->paginate($perPage);
        return $this->ajaxReturn(0, '查询成功', $list);
    }

    /*
     * 修改美容师资格证
     * author xfwed
     * date 2021.1.15
     */

    public function saveStaffCert() {
        $rule = [
            'cert_img' => 'require',
            'staff_id' => 'require',
        ];
        $msg = [
            'cert_img.require' => '，美容师资格证必须',
            'staff_id.require' => '美容师id必须',
        ];
        $all = input('post.');
        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();
            return $this->ajaxReturn(1, $error, null);
        }
        $cert_img = input('param.cert_img'); //证书图片
        $staff_id = input('param.staff_id'); //美容师id

        $cert_status = Staff::where('id', $staff_id)->value('cert_status');
        if ($cert_status == 1) {
            return $this->ajaxReturn(3, '不需要修改证书', null);
        }

        $data['cert_img'] = $cert_img;
        $data['cert_status'] = 1;

        $where['id'] = $staff_id;
        $save = Staff::where($where)->update($data);
        if ($save) {
            return $this->ajaxReturn(0, '修改成功', null);
        } else {
            return $this->ajaxReturn(3, '修改失败', null);
        }
    }

    /*
     * 美容师晋升记录
     * author xfwed
     * date 2021.1.15
     */

    public function staffExaltLogsList() {
        $staff_phone = input('param.staff_phone'); //美容师手机号
        $ifPass = input('param.ifPass'); //是否通过 0.否 1.是	
        $perPage = input('param.perPage');
        $page = input('param.page');

        $perPage = isset($perPage) ? $perPage : 10;
        $page = isset($page) ? $page : 1;

        if ($staff_phone) {
            $where['s.telephone'] = $staff_phone;
        }
        if (is_numeric($ifPass)) {
            $where['sel.ifPass'] = $ifPass;
        }

        $where = isset($where) ? $where : [];
        $list = StaffExaltLogs::alias('sel')
                ->join('staff s', 's.id = sel.staff_id', 'left')
                ->field('sel.*,s.staff_name,s.telephone,s.cert_img')
                ->where($where)
                ->order('id desc')
                ->paginate($perPage);
        return $this->ajaxReturn(0, '查询成功', $list);
    }

    /*
     * 美容师考核得分记录
     * author xfwed
     * date 2021.1.15
     */

    public function staffAssessScoreList() {
        $staff_phone = input('param.staff_phone'); //美容师手机号
        $type = input('param.type'); //0全部 1.出勤分 2.服务分
        $score_type = input('param.score_type'); //0全部 1.打卡(目前没有) 2.满勤3接单(没有) 4.高峰单 5.接单达标 6.服务基础=80 7.评价星级分 8.接单及时 9.拒绝接单 10.顾客投诉 11.顾客退单 12.仪容仪表端正 13.行为文明 14.个人卫生 15.服务周到
        $start_time = input('param.start_time');
        $end_time = input('param.end_time');
        $perPage = input('param.perPage');
        $page = input('param.page');

        $perPage = isset($perPage) ? $perPage : 10;
        $page = isset($page) ? $page : 1;

        if ($staff_phone) {
            $staff_id = Staff::where('telephone', $staff_phone)->value('id');
            $where['sas.staff_id'] = ['in', '0,' . $staff_id];
        }
        if ($type) {
            $where['sas.type'] = $type;
        }
        if ($score_type) {
            $where['sas.score_type'] = $score_type;
        }
        if ($end_time && $start_time) {
            $where['sas.add_time'] = array('between', array($start_time, $end_time));
        } elseif (empty($end_time) && $start_time) {
            $time = strtotime($start_time);
            $time2 = $time + 24 * 60 * 60;
            $time2 = date('Y-m-d H:i:s', $time2);
            $where['sas.add_time'] = array('between', array($start_time, $time2));
        }

        $where = isset($where) ? $where : [];
        $sumScore = StaffAssessScore::alias('sas')
                ->join('staff s', 's.id = sas.staff_id', 'left')
                ->where($where)
                ->sum('score');
        $data['sumScore'] = $sumScore;
        $list = StaffAssessScore::alias('sas')
                ->join('staff s', 's.id = sas.staff_id', 'left')
                ->field('sas.*,s.staff_name,s.telephone,s.cert_img')
                ->where($where)
                ->order('id desc')
                ->paginate($perPage);
        $data['list'] = $list;
        return $this->ajaxReturn(0, '查询成功', $data);
    }

    /*
     * 投诉美容师
     * author xfwed
     * date 2021.1.15
     */

    public function accuseStaff() {
        $rule = [
            'staff_id' => 'require',
            'admin_name' => 'require',
        ];
        $msg = [
            'staff_id.require' => '，美容师id必须',
            'admin_name.require' => '后台管理员名必须',
        ];
        $all = input('post.');
        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();
            return $this->ajaxReturn(1, $error, null);
        }
        $staff_id = input('param.staff_id'); //美容师id
        $admin_name = input('param.admin_name'); //后台管理员名
        $remarks = input('param.remarks');

        $data['staff_id'] = $staff_id;
        $data['type'] = 2;
        $data['score_type'] = 10;
        $data['score'] = -5;
        $data['remarks'] = '顾客400投诉，减5分';
        $data['note'] = $admin_name . ':' . $remarks;
        $data['add_time'] = date("Y-m-d 00::00:00", strtotime("+1 day"));
        $add = StaffAssessScore::insert($data);
        if ($add) {
            return $this->ajaxReturn(0, '投诉成功', null);
        } else {
            return $this->ajaxReturn(3, '投诉失败', null);
        }
    }

    /*
     * 问卷调查答案记录
     * author xfwed
     * date 2021.1.24
     */

    public function surveyLogsList() {
        $staff_phone = input('param.staff_phone'); //美容师手机号
        $type = input('param.type'); //12仪容仪表端正13行为文明14个人卫生15服务周到
        $is_deduct = input('param.is_deduct'); //1.是 2.否 已经计算	
        $perPage = input('param.perPage');
        $page = input('param.page');
        $staff_type = input('param.staff_type');//美容师类型 0全部 1品牌连锁店 2服务授权店

        $perPage = isset($perPage) ? $perPage : 10;
        $page = isset($page) ? $page : 1;

        if ($staff_phone) {
            $staff_id = Staff::where('telephone', $staff_phone)->value('id');
            $where['sl.staff_id'] = $staff_id;
        }
        if ($type) {
            $where['sl.type'] = $type;
        }
        if ($is_deduct) {
            $where['sl.is_deduct'] = $is_deduct;
        }
        if($staff_type){
            $where['s.type'] = $staff_type;
        }


        $where = isset($where) ? $where : [];
        $list = Db::name('survey_logs')->alias('sl')
                ->join('staff s', 's.id = sl.staff_id', 'left')
                ->field('sl.*,s.staff_name,s.telephone,s.cert_img,s.type staff_type')
                ->where($where)
                ->order('id desc')
                ->paginate($perPage);
        return $this->ajaxReturn(0, '查询成功', $list);
    }

    /*
     * 美容师学习文章列表
     * author xfwed
     * date 2021.03.17
     */

    public function staffArticlesList() {
        $title = input('param.title'); //标题
        $type = input('param.type'); //1.日常服务 2.护理项目 3.AI特色 4.特权活动
        $is_del = input('param.is_del'); //是否显示,1是，2否
        $is_recommend = input('param.is_recommend'); //是否推荐,1是，2否	
        $perPage = input('param.perPage');
        $page = input('param.page');
        $staff_type = input('param.staff_type');//0全部1品牌连锁店 2授权服务店 3通用	
        

        $perPage = isset($perPage) ? $perPage : 10;
        $page = isset($page) ? $page : 1;

        if ($title) {
            $where['title'] = ['like', '%' . $title . '%'];
        }
        if ($type) {
            $where['type'] = $type;
        }
        if ($is_del) {
            $where['is_del'] = $is_del;
        }
        if ($is_recommend) {
            $where['is_recommend'] = $is_recommend;
        }
        if ($staff_type) {
            $where['staff_type'] = $staff_type;
        }
        
        $where = isset($where) ? $where : [];
        $list = StaffArticles::field('id,type,title,icon,read_time,author,add_name,add_time,is_del,is_recommend,staff_type')
                ->where($where)
                ->order('id desc')
                ->paginate($perPage);
        return $this->ajaxReturn(0, '查询成功', $list);
    }

    /*
     * 添加美容师学习文章
     * author xfwed 
     * date 2021.03.17
     */

    public function addstaffArticles() {
        $rule = [
            'type' => 'require',
            'title' => 'require',
            'staff_type' => 'require',
        ];
        $msg = [
            'type.require' => '团队名称必须',
            'title.require' => '最少成员数量必须',
            'staff_type.require' => '使用范围必须',
        ];
        $all = input('param.');
        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();
            return $this->ajaxReturn(1, $error, null);
        }
        $type = input('param.type');
        $title = input('param.title');
        $content = input('param.content');
        $icon = input('param.icon');
        $video_url = input('param.video_url');
        $read_time = input('param.read_time');
        $author = input('param.author');
        $add_name = input('param.add_name');
        $add_id = input('param.add_id');
        $staff_type = input('param.staff_type');

        $data['type'] = $type;
        $data['title'] = $title;
        $data['content'] = $content;
        $data['icon'] = $icon;
        $data['video_url'] = $video_url;
        $data['read_time'] = $read_time;
        $data['author'] = $author;
        $data['add_name'] = $add_name;
        $data['add_id'] = $add_id;
        $data['add_time'] = date('Y-m-d H:i:s');
        $data['staff_type'] = $staff_type;
        $add = StaffArticles::insertGetId($data);
        if ($add) {
            return $this->ajaxReturn(0, '添加成功', null);
        } else {
            return $this->ajaxReturn(3, '添加失败', null);
        }
    }

    /*
     * 修改美容师学习文章
     * author xfwed 
     * date 2021.03.17
     */

    public function savestaffArticles() {
        $requestType = input('param.requestType');
        $id = input('param.id');
        if ($requestType == 1) {//1修改前获取信息 2提交修改
            $articlesInfo = StaffArticles::where('id', $id)->find();
            return $this->ajaxReturn(0, '查询成功', $articlesInfo);
        } else {
            $rule = [
                'type' => 'require',
                'title' => 'require',
                'staff_type' => 'require',
            ];
            $msg = [
                'type.require' => '团队名称必须',
                'title.require' => '最少成员数量必须',
                'staff_type.require' => '适用范围必须',
            ];
            $all = input('param.');
            $validate = new Validate($rule, $msg);
            if (!$validate->check($all)) {
                $error = $validate->getError();
                return $this->ajaxReturn(1, $error, null);
            }
            $type = input('param.type');
            $title = input('param.title');
            $content = input('param.content');
            $icon = input('param.icon');
            $video_url = input('param.video_url');
            $read_time = input('param.read_time');
            $author = input('param.author');
            $add_name = input('param.add_name');
            $add_id = input('param.add_id');
            $staff_type = input('param.staff_type');

            $data['type'] = $type;
            $data['title'] = $title;
            $data['content'] = $content;
            $data['icon'] = $icon;
            $data['video_url'] = $video_url;
            $data['read_time'] = $read_time;
            $data['author'] = $author;
            $data['add_name'] = $add_name;
            $data['add_id'] = $add_id;
            $data['add_time'] = date('Y-m-d H:i:s');
            $data['staff_type'] = $staff_type;
            $save = StaffArticles::where('id', $id)->update($data);
            if ($save) {
                return $this->ajaxReturn(0, '修改成功', null);
            } else {
                return $this->ajaxReturn(3, '修改失败', null);
            }
        }
    }

    /*
     * 删除美容师学习文章
     * author xfwed 
     * date 2021.03.17
     */

    public function delstaffArticles() {
        $rule = [
            'id' => 'require',
            'is_del' => 'require',
        ];
        $msg = [
            'id.require' => '文章id必须',
            'is_del.require' => '状态必须',
        ];
        $all = input('post.');
        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();
            return $this->ajaxReturn(1, $error, null);
        }
        $id = input('param.id');
        $is_del = input('param.is_del'); //是否显示,1是，2否
        $result = StaffArticles::where('id', $id)
                ->update(['is_del' => $is_del]);
        if ($result) {
            return $this->ajaxReturn(0, '操作成功', null);
        } else {
            return $this->ajaxReturn(3, '操作失败', null);
        }
    }

    /*
     * 推荐美容师学习文章
     * author xfwed 
     * date 2021.03.17
     */

    public function recommendstaffArticles() {
        $rule = [
            'id' => 'require',
            'is_recommend' => 'require',
        ];
        $msg = [
            'id.require' => '文章id必须',
            'is_recommend.require' => '状态必须',
        ];
        $all = input('post.');
        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();
            return $this->ajaxReturn(1, $error, null);
        }
        $id = input('param.id');
        $is_recommend = input('param.is_recommend'); //是否显示,1是，2否
        $result = StaffArticles::where('id', $id)
                ->update(['is_recommend' => $is_recommend]);
        if ($result) {
            return $this->ajaxReturn(0, '推荐成功', null);
        } else {
            return $this->ajaxReturn(3, '推荐失败', null);
        }
    }

    /*
     * 美容师知识题目列表
     * author xfwed
     * date 2021.03.18
     */

    public function staffSubjectList() {
        $content = input('param.content'); //标题
        $type = input('param.type'); //1.牛刀小试 2.初露锋芒 3.大显身手 4.冲击最强
        $is_del = input('param.is_del'); //是否显示,1是，2否
        $select_type = input('param.select_type'); //1.单选 2.多选
        $perPage = input('param.perPage');
        $page = input('param.page');
        $staff_type = input('param.staff_type');//0全部1品牌连锁店 2授权服务店 3通用

        $perPage = isset($perPage) ? $perPage : 10;
        $page = isset($page) ? $page : 1;

        if ($content) {
            $where['content'] = ['like', '%' . $content . '%'];
        }
        if ($type) {
            $where['type'] = $type;
        }
        if ($is_del) {
            $where['is_del'] = $is_del;
        }
        if ($select_type) {
            $where['select_type'] = $select_type;
        }
        if($staff_type){
            $where['staff_type'] = $staff_type;
        }

        $where = isset($where) ? $where : [];
        $list = StaffSubject::where($where)
                ->field('id,type,content,select_type,is_del,add_time,staff_type')
                ->order('id desc')
                ->paginate($perPage);
        return $this->ajaxReturn(0, '查询成功', $list);
    }

    /*
     * 添加美容师知识题目
     * author xfwed 
     * date 2021.03.18
     */

    public function addstaffSubject() {
        $rule = [
            'type' => 'require',
            'content' => 'require',
            'staff_type' => 'require',
        ];
        $msg = [
            'type.require' => '类型必须必须',
            'content.require' => '题目内容必须',
            'staff_type.require' => '适用范围必须',
        ];
        $all = input('param.');
        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();
            return $this->ajaxReturn(1, $error, null);
        }
        $type = input('param.type');
        $content = input('param.content');
        $img = input('param.img');
        $video_url = input('param.video_url');
        $select_json = input('param.select_json');
        $select_type = input('param.select_type');
        $right_answer = input('param.right_answer');
        $analysis = input('param.analysis');
        $staff_type = input('param.staff_type');

        $data['type'] = $type;
        $data['content'] = $content;
        $data['img'] = $img;
        $data['video_url'] = $video_url;
        $data['select_json'] = $select_json;
        $data['select_type'] = $select_type;
        $data['right_answer'] = $right_answer;
        $data['analysis'] = $analysis;
        $data['add_time'] = date('Y-m-d H:i:s');
        $data['staff_type'] = $staff_type;
        $add = StaffSubject::insertGetId($data);
        if ($add) {
            return $this->ajaxReturn(0, '添加成功', null);
        } else {
            return $this->ajaxReturn(3, '添加失败', null);
        }
    }

    /*
     * 修改美容师知识题目
     * author xfwed 
     * date 2021.03.17
     */

    public function savestaffSubject() {
        $requestType = input('param.requestType');
        $id = input('param.id');
        if ($requestType == 1) {//1修改前获取信息 2提交修改
            $articlesInfo = StaffSubject::where('id', $id)->find();
            return $this->ajaxReturn(0, '查询成功', $articlesInfo);
        } else {
            $rule = [
                'type' => 'require',
                'content' => 'require',
                'staff_type' => 'require',
            ];
            $msg = [
                'type.require' => '类型必须必须',
                'content.require' => '题目内容必须',
                'staff_type.require' => '适用范围必须',
            ];
            $all = input('param.');
            $validate = new Validate($rule, $msg);
            if (!$validate->check($all)) {
                $error = $validate->getError();
                return $this->ajaxReturn(1, $error, null);
            }
            $type = input('param.type');
            $content = input('param.content');
            $img = input('param.img');
            $video_url = input('param.video_url');
            $select_json = input('param.select_json');
            $select_type = input('param.select_type');
            $right_answer = input('param.right_answer');
            $analysis = input('param.analysis');
            $staff_type = input('param.staff_type');

            $data['type'] = $type;
            $data['content'] = $content;
            $data['img'] = $img;
            $data['video_url'] = $video_url;
            $data['select_json'] = $select_json;
            $data['select_type'] = $select_type;
            $data['right_answer'] = $right_answer;
            $data['analysis'] = $analysis;
            $data['add_time'] = date('Y-m-d H:i:s');
            $data['staff_type'] = $staff_type;
            $save = StaffSubject::where('id', $id)->update($data);
            if ($save) {
                return $this->ajaxReturn(0, '修改成功', null);
            } else {
                return $this->ajaxReturn(3, '修改失败', null);
            }
        }
    }

    /*
     * 删除美容师知识题目
     * author xfwed 
     * date 2021.03.17
     */

    public function delstaffSubject() {
        $rule = [
            'id' => 'require',
            'is_del' => 'require',
        ];
        $msg = [
            'id.require' => '题目id必须',
            'is_del.require' => '状态必须',
        ];
        $all = input('post.');
        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();
            return $this->ajaxReturn(1, $error, null);
        }
        $id = input('param.id');
        $is_del = input('param.is_del'); //是否显示,1是，2否
        $result = StaffSubject::where('id', $id)
                ->update(['is_del' => $is_del]);
        if ($result) {
            return $this->ajaxReturn(0, '操作成功', null);
        } else {
            return $this->ajaxReturn(3, '操作失败', null);
        }
    }

    /*
     * 导入美容师知识题目
     * author xfwed
     * date 2021.03.19
     */

    public function importStaffSubject() {
        if (!empty($_FILES)) {
            header("Content-Type:text/html;charset=utf8");

            $file = request()->file('import');
            $fileInfo = $file->move(ROOT_PATH . '../kkmimg/kkmai/subject', date('Ymdhis'));
//            echo "<pre/>";
//            print_r($fileInfo['name']);
            // 上传文件
            if (!$fileInfo) {
                return $this->ajaxReturn(3, '上传失败', null);
            }
            $fileName1 = 'kkmai/subject/' . str_replace(DS, '/', $fileInfo->getSaveName());
            $fileName = explode('.', $fileName1);
            //$fileName1="http://127.0.0.1/kkmimg/".$fileName1;
            $fileName1 = ROOT_PATH . '../kkmimg/' . $fileName1;
            //print_r($fileName1);

            Vendor("PHPExcel.IOFactory");
            if ($fileName[1] == 'xls') {
                $reader = \PHPExcel_IOFactory::createReader('Excel5'); //设置以Excel2007格式  
            } elseif ($fileName[1] == 'xlsx') {
                $reader = \PHPExcel_IOFactory::createReader('Excel2007'); //设置以Excel2007格式  
            }
            $PHPExcel = $reader->load($fileName1); // 载入excel文件  
            $sheet = $PHPExcel->getSheet(0); // 读取第一個工作表  
            $highestRow = $sheet->getHighestRow(); // 取得总行数  
            $highestColumn = $sheet->getHighestColumn(); // 取得总列数  
            //print_r($highestColumn);
            // 循环获取表中的数据，$currentRow表示当前行，从那行开始读取数据，索引值为0开始
            for ($currentRow = 5; $currentRow <= $highestRow; $currentRow++) {
                // 从哪开始A标识第1列
                for ($currentColumn = 'A'; $currentColumn <= $highestColumn; $currentColumn++) {
                    // 数据坐标
                    $address = $currentColumn . $currentRow;
                    // 获取到数据保存到$arr中
                    $sourceData[$currentRow][$currentColumn] = $sheet->getCell($address)->getValue();
                }
            }
//            echo '<pre />';
//            print_r($sourceData);die;
            //查询是否审核通过
            for ($i = 5; $i < count($sourceData) + 5; $i++) {
                $type = $sourceData[$i]['B']; //1.牛刀小试 2.初露锋芒 3.大显身手 4.冲击最强
                $content = $sourceData[$i]['C']; //题目内容
                $select_json = $sourceData[$i]['D']; //选项
                $select_type = $sourceData[$i]['E']; //1.单选 2.多选
                $right_answer = $sourceData[$i]['F']; //正确答案
                $analysis = $sourceData[$i]['G']; //题目解析
                $staff_type = $sourceData[$i]['H']; //适用范围 1品牌连锁店 2授权服务店 3通用	
                $staffSubjectRow = StaffSubject::where('content', $content)
                        ->where('is_del', 1)
                        ->find();
                if ($staffSubjectRow) {
                    $sourceData[$i]['J'] = 2; //1是2否导入成功
                    $sourceData[$i]['K'] = '已经包含此题目';
                } else {
                    $data['type'] = $type;
                    $data['content'] = $content;
                    $data['select_json'] = $select_json;
                    $data['select_type'] = $select_type;
                    $data['right_answer'] = $right_answer;
                    $data['analysis'] = $analysis;
                    $data['add_time'] = date('Y-m-d H:i:s');
                    $data['staff_type'] = $staff_type;
                    $add = StaffSubject::insertGetId($data);
                    if ($add) {
                        $sourceData[$i]['J'] = 1; //1是2否导入成功
                        $sourceData[$i]['K'] = '导入成功';
                    } else {
                        $sourceData[$i]['J'] = 2; //1是2否导入成功
                        $sourceData[$i]['K'] = '导入失败';
                    }
                }
            }
            $xlsName = "批量导入学习题目";
            $this->exportorderExcel($xlsName, $sourceData);
//            echo "<pre/>";
//            print_r($sourceData);
//            die;
            $this->success('导入成功！');
        } else {
            $this->error("请选择上传的文件");
        }
    }

    /*
     * 导出美容师知识题目
     * author wxf
     * date 2021-03-19
     */

    public function exportorderExcel($expTitle, $expTableData) {
        $xlsTitle = iconv('utf-8', 'gb2312', $expTitle); //文件名称
        $fileName = $xlsTitle . date('_YmdHis'); //or $xlsTitle 文件名称可根据自己情况设定
        $ii = 3;
        Vendor('PHPExcel.PHPExcel');
        $objPHPExcel = new \PHPExcel();
        $cellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ');
        $objPHPExcel->getActiveSheet(0)->mergeCells('A1:' . $cellName[6 - 1] . '1'); //合并单元格
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', $expTitle . '  Export time:' . date('Y-m-d H:i:s'));
        $objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setSize(18);
        $objPHPExcel->getActiveSheet()->getStyle('A1')->applyFromArray(//居中加粗
                array(
                    'font' => array(
                        'bold' => true
                    ),
                    'alignment' => array(
                        'horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_CENTER
                    )
                )
        );
        $objPHPExcel->getActiveSheet()->getRowDimension('1')->setRowHeight(30); // 第一行的默认高度
        $objPHPExcel->getActiveSheet()->getRowDimension('2')->setRowHeight(25); // 第一行的默认高度
        $objPHPExcel->getActiveSheet()->getDefaultRowDimension()->setRowHeight(20); // 所有单元格默认高度
        $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setAutoSize(true); //设置宽width
        $objPHPExcel->getActiveSheet()->getColumnDimension('L')->setWidth(16); //设置宽width
        $objPHPExcel->getActiveSheet()->getColumnDimension('M')->setWidth(16); //设置宽width
        $objPHPExcel->getActiveSheet()->getStyle('A1')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER); //垂直居中
        $objPHPExcel->getActiveSheet()->getStyle('2')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER); //垂直居中
        $styleArray = array(
            'borders' => array(
                'allborders' => array(
                    //'style' => PHPExcel_Style_Border::BORDER_THICK,//边框是粗的  
                    'style' => \PHPExcel_Style_Border::BORDER_THIN, //细边框  
                //'color' => array('argb' => 'FFFF0000'),  
                ),
            ),
        );
        $objPHPExcel->getActiveSheet()->getStyle('A1:F' . (count($expTableData) + 2))->applyFromArray($styleArray); //这里就是画出从单元格A5到N5的边框，看单元格最右边在哪哪个格就把这个N改为那个字母替代  


        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A2', "编号");
        $objPHPExcel->getActiveSheet()->getStyle('A2')->applyFromArray(array('font' => array('bold' => true)));
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('B2', "类型");
        $objPHPExcel->getActiveSheet()->getStyle('B2')->applyFromArray(array('font' => array('bold' => true)));
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('C2', "题目内容");
        $objPHPExcel->getActiveSheet()->getStyle('C2')->applyFromArray(array('font' => array('bold' => true)));
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('D2', "选项");
        $objPHPExcel->getActiveSheet()->getStyle('D2')->applyFromArray(array('font' => array('bold' => true)));
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('E2', "题目类型");
        $objPHPExcel->getActiveSheet()->getStyle('E2')->applyFromArray(array('font' => array('bold' => true)));
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('F2', "正确答案");
        $objPHPExcel->getActiveSheet()->getStyle('F2')->applyFromArray(array('font' => array('bold' => true)));
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('G2', "题目解析");
        $objPHPExcel->getActiveSheet()->getStyle('G2')->applyFromArray(array('font' => array('bold' => true)));
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('H2', "适用范围");
        $objPHPExcel->getActiveSheet()->getStyle('H2')->applyFromArray(array('font' => array('bold' => true)));
         $objPHPExcel->setActiveSheetIndex(0)->setCellValue('I2', "备注");
        $objPHPExcel->getActiveSheet()->getStyle('I2')->applyFromArray(array('font' => array('bold' => true)));
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('J2', "1是2否导入成功");
        $objPHPExcel->getActiveSheet()->getStyle('J2')->applyFromArray(array('font' => array('bold' => true)));
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('K2', "导入备注");
        $objPHPExcel->getActiveSheet()->getStyle('K2')->applyFromArray(array('font' => array('bold' => true)));

        foreach ($expTableData as $key => $val) {
            $tt = 'A' . $ii;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($tt, " " . $val['A']); //加  “ ”防止用科学计数法，中间必须有空格，否则无效
            $tt = 'B' . $ii;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($tt, " " . $val['B']);
            $tt = 'C' . $ii;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($tt, $val['C']);
            $tt = 'D' . $ii;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($tt, $val['D']);
            $tt = 'E' . $ii;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($tt, $val['E']);
            $tt = 'F' . $ii;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($tt, " " . $val['F']);
            $tt = 'G' . $ii;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($tt, " " . $val['G']);
            $tt = 'H' . $ii;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($tt, " " . $val['H']);
            $tt = 'I' . $ii;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($tt, " " . $val['I']);
            $tt = 'J' . $ii;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($tt, " " . $val['J']);
            $tt = 'K' . $ii;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($tt, " " . $val['K']);
            $ii++;
        }
        ob_end_clean();
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Type: application/vnd.ms-excel;charset=utf-8');
        header('Content-Disposition: attachment;filename="' . $fileName . '.xls"');  //日期为文件名后缀
        header('Cache-Control: max-age=0');
        header("Content-type:application/octet-stream");
        header("Accept-Ranges:bytes");
        header("Pragma: no-cache");
        header("Expires: 0");
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        exit;
    }

    /*
     * 积分明细
     * author xfwed 
     * date 2021.04.07
     */

    public function getIntegralLog() {
        $rule = [
            'staffId' => 'require',
            'type' => 'require',
            'perPage' => 'integer|egt:1',
            'page' => 'integer|egt:1',
        ];
        $msg = [
            'staffId.require' => '美容师id必须',
            'type.require' => '类型必须',
            'perPage.integer' => '每页数量为数字',
            'perPage.egt' => '每页数量最小为1',
            'page.integer' => '当前页数为数字',
            'page.egt' => '当前页数最小为1',
        ];
        $all = input('param.');
        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();
            return $this->ajaxReturn(1, $error, null);
        }
        $staffId = input('param.staffId');
        $type = input('param.type'); //0.全部 1.收入 2.支出
        $perPage = isset($all['perPage']) ? $all['perPage'] : 20;
        $page = isset($all['page']) ? $all['page'] : 0;

        $ApiPath = config('appconfig.ApiPath8890');
        $relust = Utils::curlGet($ApiPath . '/staff/study/getIntegralLog/' . $staffId . '/' . $type . '/' . $page . '/' . $perPage);
        $relust = json_decode($relust, true);
        if ($relust['code'] == 0) {
            return $this->ajaxReturn(0, '查询成功', $relust['data']);
        } else {
            return $this->ajaxReturn(3, '查询失败', null);
        }
    }

    /*
     * 历史成绩
     * author xfwed 
     * date 2021.04.07
     */

    public function scoreLog() {
        $rule = [
            'staffId' => 'require',
            'type' => 'require',
            'perPage' => 'integer|egt:1',
            'page' => 'integer|egt:1',
        ];
        $msg = [
            'staffId.require' => '美容师id必须',
            'type.require' => '类型必须',
            'perPage.integer' => '每页数量为数字',
            'perPage.egt' => '每页数量最小为1',
            'page.integer' => '当前页数为数字',
            'page.egt' => '当前页数最小为1',
        ];
        $all = input('param.');
        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();
            return $this->ajaxReturn(1, $error, null);
        }
        $staffId = input('param.staffId');
        $type = input('param.type'); //1.日常服务 2.护理项目 3.AI特色 4.特权活动	
        $perPage = isset($all['perPage']) ? $all['perPage'] : 20;
        $page = isset($all['page']) ? $all['page'] : 0;

        $relust = Db::name('staff_examination_log')
                ->where('type', $type)
                ->where('staff_id', $staffId)
                ->order('if_pass asc')
                ->field('answered,no_answer', TRUE)
                ->paginate($perPage);
        if ($relust) {
            return $this->ajaxReturn(0, '查询成功', $relust);
        } else {
            return $this->ajaxReturn(3, '查询失败', null);
        }
    }

    /*
     * 今日统计
     * author xfwed 
     * date 2021.04.08
     */

    public function todayTotal() {
        $rule = [
            'staffId' => 'require',
            'dateType' => 'require',
        ];
        $msg = [
            'staffId.require' => '美容师id必须',
            'dateType.require' => '类型必须',
        ];
        $all = input('param.');
        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();
            return $this->ajaxReturn(1, $error, null);
        }
        $staffId = input('param.staffId');
        $dateType = input('param.dateType'); //	0.本日 1.本周 2.本月 3.全部 4.自定义
        $startDate = input('param.startDate'); //dateType == 4的时候必须
        $endDate = input('param.endDate'); //dateType == 4的时候必须

        $ApiPath = config('appconfig.ApiPath8890');
        $relust = Utils::curlGet($ApiPath . '/staff/todayTotal?staffId=' . $staffId . '&dateType=' . $dateType . '&startDate=' . $startDate . '&endDate=' . $endDate);
        $relust = json_decode($relust, true);
        if ($relust['code'] == 0) {
            return $this->ajaxReturn(0, '查询成功', $relust['data']);
        } else {
            return $this->ajaxReturn(3, '查询失败', null);
        }
    }

    /*
     * 今日统计明细
     * author xfwed 
     * date 2021.04.08
     */

    public function todayTotalDetails() {
        $rule = [
            'staffId' => 'require',
            'fundtype' => 'require',
            'dateType' => 'require',
            'perPage' => 'integer|egt:1',
            'page' => 'integer|egt:1',
        ];
        $msg = [
            'staffId.require' => '美容师id必须',
            'fundtype.require' => '类型必须',
            'dateType.require' => '类型必须',
            'perPage.integer' => '每页数量为数字',
            'perPage.egt' => '每页数量最小为1',
            'page.integer' => '当前页数为数字',
            'page.egt' => '当前页数最小为1',
        ];
        $all = input('param.');
        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();
            return $this->ajaxReturn(1, $error, null);
        }
        $staffId = input('param.staffId');
        $fundtype = $all['fundtype']; //0服务额1商品额2服务人次3服务人数4预约订单5特权开通6推广人数7推广金额
        $dateType = input('param.dateType'); //	0.本日 1.本周 2.本月 3.全部 4.自定义
        $startDate = input('param.startDate'); //dateType == 4的时候必须
        $endDate = input('param.endDate'); //dateType == 4的时候必须

        $perPage = isset($all['perPage']) ? $all['perPage'] : 20;
        $page = isset($all['page']) ? $all['page'] : 0;

        $ApiPath = config('appconfig.ApiPath8890');
        $relust = Utils::curlGet($ApiPath . '/staff/todayTotalDetails?staffId=' . $staffId . '&fundtype=' . $fundtype . '&dateType=' . $dateType . '&startDate=' . $startDate . '&endDate=' . $endDate . '&page=' . $page . '&pageSize=' . $perPage);
        $relust = json_decode($relust, true);
        if ($relust['code'] == 0) {
            return $this->ajaxReturn(0, '查询成功', $relust['data']);
        } else {
            return $this->ajaxReturn(3, '查询失败', null);
        }
    }

    /*
     * 美容师时间管理
     * author xfwed 
     * date 2021.04.08
     */

    public function staffTimeOccupy() {
        $rule = [
            'perPage' => 'integer|egt:1',
            'page' => 'integer|egt:1',
        ];
        $msg = [
            'perPage.integer' => '每页数量为数字',
            'perPage.egt' => '每页数量最小为1',
            'page.integer' => '当前页数为数字',
            'page.egt' => '当前页数最小为1',
        ];
        $all = input('param.');
        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();
            return $this->ajaxReturn(1, $error, null);
        }
        $perPage = isset($all['perPage']) ? $all['perPage'] : 20;
        $page = isset($all['page']) ? $all['page'] : 0;

        $type = input('param.type'); //占用类型: -1全部 0.请假 1.项目预约	
        $is_del = input('param.is_del'); //-1全部0.有效 1.无效
        $staff_phone = input('param.staff_phone'); //美容师手机号
        $store_phone = input('param.store_name'); //店铺手机号
        $store_type = input('param.store_type');//店铺类型 0全部 1品牌连锁店 2服务授权店	
        $staff_type = input('param.staff_type');//美容师类型 0全部 1品牌连锁店 2服务授权店
        if ($type == 0 || $type == 1) {
            $where['tor.type'] = $type;
        }
        if ($is_del == 0 || $is_del == 1) {
            $where['tor.is_del'] = $is_del;
        }
        if ($staff_phone) {
            $where['s.telephone'] = $staff_phone;
        }
        if ($store_phone) {
            $where['st.store_name'] = ['like','%'.$store_phone.'%'];
        }
        if($store_type){
            $where['st.type'] = $store_type;
        }

        if($staff_type){
            $where['s.type'] = $staff_type;
        }


        $where = isset($where) ? $where : [];
        $relust = Db::name('time_occupy_record')
                ->alias('tor')
                ->join('staff s', 's.id = tor.staff_id', 'left')
                ->join('store st', 'st.id = tor.store_id', 'left')
                ->join('store_room sr', 'sr.id = tor.room_id', 'left')
                ->join('store_room_bed srb', 'srb.id = tor.bed_id', 'left')
                ->where($where)
                ->order('add_time desc')
                ->field('tor.*,s.staff_name,s.type staff_type,st.store_name,st.type store_type,sr.room_name,srb.bed_name')
                ->paginate($perPage);
        if ($relust) {
            return $this->ajaxReturn(0, '查询成功', $relust);
        } else {
            return $this->ajaxReturn(3, '查询失败', null);
        }
    }

    /*
     * 招募美容师加入理由标签
     * 日期 2021-04-16
     */

    public function staffEnlistLabel() {
        $list = Db::table('sys_dictionary')
                ->where('type', 'STAFF_ENLIST_LABEL')
                //->where('active', 0)
                ->field('id,view,active')
                ->order('active asc id desc')
                ->select();
        return Utils::ajaxReturn(0, '查询成功', $list);
    }

    /*
     * 添加招募美容师加入理由标签
     * 日期 2021-04-16
     */

    public function addStaffEnlistLabel() {
        $name = input('param.name'); //标签名称  多个用逗号隔开
        $name = explode(",", $name);
        for ($i = 0; $i < count($name); $i++) {
            Db::table('sys_dictionary')
                    ->insert([
                        'code' => 'label',
                        'view' => $name[$i],
                        'type' => 'STAFF_ENLIST_LABEL',
                        'desc' => '招募美容师加入理由标签',
            ]);
        }
        return Utils::ajaxReturn(0, '添加成功', null);
    }

    /*
     * 隐藏招募美容师加入理由标签
     * 日期 2021-04-16
     */

    public function delStaffEnlistLabel() {
        $id = input('param.id'); //标签名称  多个用逗号隔开
        $active = input('param.active');

        $relust = Db::table('sys_dictionary')->where('id', $id)->update(['active' => $active]);
        if ($relust) {
            return Utils::ajaxReturn(0, '操作成功', null);
        } else {
            return Utils::ajaxReturn(0, '操作失败', null);
        }
    }
    
    /*
     * 美容师招募列表
     * author xfwed 
     * date 2021.04.16
     */

    public function staffEnlistList() {
        $rule = [
            'perPage' => 'integer|egt:1',
            'page' => 'integer|egt:1',
        ];
        $msg = [
            'perPage.integer' => '每页数量为数字',
            'perPage.egt' => '每页数量最小为1',
            'page.integer' => '当前页数为数字',
            'page.egt' => '当前页数最小为1',
        ];
        $all = input('param.');
        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();
            return $this->ajaxReturn(1, $error, null);
        }
        $perPage = isset($all['perPage']) ? $all['perPage'] : 20;
        $page = isset($all['page']) ? $all['page'] : 0;

        $custom_name = input('param.custom_name'); //用户姓名
        $custom_phone = input('param.custom_phone'); //用户手机号
        $status = input('param.status'); //0全部1待处理2未加入3加入中4已加入	
        
        if ($custom_name) {
            $where['c.custom_name'] = ['like','%'.$custom_name.'%'];
        }
        if ($custom_phone) {
            $where['c.custom_phone'] = $custom_phone;
        }
        if ($status) {
            $where['s.status'] = $status;
        }

        $where = isset($where) ? $where : [];
        $list = StaffEnlist::alias('s')
                ->join('custom c','c.id = s.ctm_id','left')
                ->where($where)
                ->order('s.add_time desc')
                ->field('s.*,c.custom_name,c.custom_phone')
                ->paginate($perPage)
                ->each(function($item, $key){
                    $reason = $item['reason'];
                    $view = Db::table('sys_dictionary')->where('id','in',$reason)->column('view');
                    $item['reason'] = implode(',', $view);
                });
        
        return $this->ajaxReturn(0, '查询成功', $list);
    }
    
    /*
     * 美容师招募修改状态
     * 日期 2021-04-16
     */

    public function saveStaffEnlist() {
        $id = input('param.id'); //标签名称  多个用逗号隔开
        $status = input('param.status');//状态
        
        $result = StaffEnlist::where('id',$id)->update(['status'=>$status]);

        if ($result) {
            return Utils::ajaxReturn(0, '修改成功', null);
        } else {
            return Utils::ajaxReturn(0, '修改失败', null);
        }
    }
    
    /*
     * 美容师面试通过
     * 日期 2021-05-12
     */

    public function saveinterview() {
        $id = input('param.id'); 
        
        $result = Staff::where('id',$id)->update(['interview'=>1]);

        if ($result) {
            return Utils::ajaxReturn(0, '面试通过', null);
        } else {
            return Utils::ajaxReturn(0, '已经通过了', null);
        }
    }
    
    /*
     * 美容师补贴充值记录
     * 日期 2021-06-15
     */

    public function subsidyRechargeList() {
        $start_time = input('param.start_time'); 
        $end_time = input('param.end_time'); 
        $store_id = input('param.store_id');
        $perPage = input('param.perPage');
        $page = input('param.page');
        $type = input('param.type');	//0全部1.后台充值 2.店铺转存
        $store_type = input('param.store_type');//店铺类型 0全部 1品牌连锁店 2服务授权店
        
        if($start_time && $end_time){
            $where['sr.add_time'] = ['between',[$start_time,$end_time]];
        }
        if($store_id){
            $where['sr.store_id'] = $store_id;
        }
        if($type){
            $where['sr.type'] = $type;
        }
        if($store_type){
            $where['s.type'] = $store_type;
        }
        
        $perPage = isset($perPage) ? $perPage : 10;
        $page = isset($page) ? $page : 1;
        
        $where = isset($where)?$where:[];
        $list = Db::name('subsidy_recharge')
                ->alias('sr')
                ->join('store s','s.id = sr.store_id','left')
                ->field('sr.*,s.store_name,s.subsidy_money,s.type store_type')
                ->where($where)
                ->paginate($perPage);
        $data['list'] = $list;
        //累计充值239.02元补贴，剩余3555.03未补贴
        if($store_id){
            $data['rechargeMoney'] = Db::name('subsidy_recharge')->where('store_id',$store_id)->sum('money');//充值金额
            $data['surplusMoney'] = Db::name('store')->where('id',$store_id)->sum('subsidy_money');//剩余补贴金额
        }  else {
            $data['rechargeMoney'] = Db::name('subsidy_recharge')->sum('money');//充值金额
            $data['surplusMoney'] = Db::name('store')->sum('subsidy_money');//剩余补贴金额
        }
        
        return Utils::ajaxReturn(0, '查询成功', $data);
    }
    
    /*
     * 美容师补贴充值
     * 日期 2021-06-15
     */

    public function addSubsidyRecharge() {
        $store_id = input('param.store_id'); 
        $money = input('param.money'); 
        $why = input('param.why');
        $admin_name = input('param.admin_name');
        
        Db::startTrans();
        $data['store_id'] = $store_id;
        $data['money'] = $money;
        $data['why'] = $why;
        $data['admin_name'] = $admin_name;
        $data['title'] = '后台充值';
        $data['add_time'] = date('Y-m-d H:i:s');
        $insert = Db::name('subsidy_recharge')->insert($data);
        //更新店铺剩余补贴金额
        $saveStore = Db::name('store')
                ->where('id',$store_id)
                ->setInc('subsidy_money',$money);
        if($insert && $saveStore){
           Db::commit();
           return Utils::ajaxReturn(0, '充值成功', null);
        }  else {
           Db::rollback(); 
           return Utils::ajaxReturn(3, '充值失败', null);
        }
    }
    
    /*
     * 美容师补贴活动列表
     * 日期 2021-06-15
     */

    public function subsidySetupList() {
        $start_time = input('param.start_time'); 
        $end_time = input('param.end_time'); 
        $store_id = input('param.store_id');
        $status = input('param.status');
        $perPage = input('param.perPage');
        $page = input('param.page');
        $store_type = input('param.store_type');//店铺类型 0全部 1品牌连锁店 2服务授权店	
        $staff_type = input('param.staff_type');//美容师类型 0全部 1品牌连锁店 2服务授权店
        
        if($start_time && $end_time){
            $where['ss.add_time'] = ['between',[$start_time,$end_time]];
        }
        if($store_id){
            $where['ss.store_id'] = $store_id;
        }
        if($status){
            $where['ss.status'] = $status;
        }
        if($store_type){
            $where['s.type'] = $store_type;
        }
        if($staff_type){
            $where['ss.staff_type'] = $staff_type;
        }
        
        $perPage = isset($perPage) ? $perPage : 10;
        $page = isset($page) ? $page : 1;
        
        $where = isset($where)?$where:[];
        $list = Db::name('subsidy_setup')
                ->alias('ss')
                ->join('store s','s.id = ss.store_id','left')
                ->field('ss.*,s.store_name,s.type store_type')
                ->where($where)
                ->paginate($perPage);

        return Utils::ajaxReturn(0, '查询成功', $list);
    }
    
    /*
     * 创建美容师补贴活动
     * 日期 2021-06-15
     */

    public function addSubsidySetup() {
        $store_id = input('param.store_id'); 
        $min_service = input('param.min_service'); 
        $min_money = input('param.min_money');
        $max_service = input('param.max_service');
        $max_money = input('param.max_money');
        $start_time = input('param.start_time');
        $end_time = input('param.end_time');
        $why = input('param.why');
        $staff_type = input('param.staff_type');
        //查询该店铺是否有进行中的活动
        $row = Db::name('subsidy_setup')
                ->where('status',2)
                ->where('end_time','>',date('Y-m-d H:i:s'))
                ->where('store_id',$store_id)
                ->find();
        if($row){
            return Utils::ajaxReturn(3, '该店铺有进行中的活动,请先结束', null);
        }
        //单数中间不能有空缺
        $c = $max_service - $min_service;
        if($c != 1){
            return Utils::ajaxReturn(3, '单数设置有误', null);
        }
        //查询店铺可用补贴余额
        $storeRow = Db::name('store')
                ->where('id',$store_id)
                ->value('subsidy_money');
        if($storeRow <= 0){
            return Utils::ajaxReturn(3, '店铺补贴金额不足', null);
        }
        
        $data['store_id'] = $store_id;
        $data['min_service'] = $min_service;
        $data['min_money'] = $min_money;
        $data['max_service'] = $max_service;
        $data['max_money'] = $max_money;
        $data['start_time'] = $start_time;
        $data['end_time'] = $end_time;
        $data['why'] = $why;
        $data['status'] = 2;
        $data['staff_type'] = $staff_type;
        $data['add_time'] = date('Y-m-d H:i:s');
        $insert = Db::name('subsidy_setup')->insert($data);
        
        if($insert){
           return Utils::ajaxReturn(0, '创建成功', null);
        }  else {
           return Utils::ajaxReturn(3, '创建失败', null);
        }
    }
    
    /*
     * 结束补贴
     * 日期 2021-06-16
     */

    public function endSubsidy() {
        $id = input('param.id'); //补贴id
        $store_id = input('param.store_id');//复制给的店铺id
        $row = Db::name('subsidy_setup')
                ->where('id',$id)
                ->update(['status'=>3]);
        if($row){
           return Utils::ajaxReturn(0, '结束成功', null);
        }  else {
           return Utils::ajaxReturn(3, '结束失败', null);
        }
    }
    
    /*
     * 复制补贴
     * 日期 2021-06-16
     */

    public function copySubsidy() {
        $id = input('param.id'); //要复制的补贴id
        $store_id = input('param.store_id');//复制给的店铺id
        $row = Db::name('subsidy_setup')
                ->where('id',$id)
                ->field('id',TRUE)
                ->find();
        
        //查询该店铺是否有进行中的活动
        $row1 = Db::name('subsidy_setup')
                ->where('status',2)
                ->where('end_time','>',date('Y-m-d H:i:s'))
                ->where('store_id',$store_id)
                ->find();
        if($row1){
            return Utils::ajaxReturn(3, '该店铺有进行中的活动,请先结束', null);
        }
        
        //查询店铺可用补贴余额
        $storeRow = Db::name('store')
                ->where('id',$store_id)
                ->value('subsidy_money');
        if($storeRow <= 0){
            return Utils::ajaxReturn(3, '店铺补贴金额不足', null);
        }
        
        $row['store_id'] = $store_id;
        $row['add_time'] = date('Y-m-d H:i:s');
        $insert = Db::name('subsidy_setup')->insert($row);

        if($insert){
           return Utils::ajaxReturn(0, '复制成功', null);
        }  else {
           return Utils::ajaxReturn(3, '复制失败', null);
        }
    }
    
    /*
     * 美容师补贴记录
     * 日期 2021-06-16
     */

    public function subsidyList() {
        $id = input('param.id');//补贴活动id  从活动列表 点击查看补贴记录 时传这个参数
        $start_time = input('param.start_time'); 
        $end_time = input('param.end_time'); 
        $staff_name = input('param.staff_name');//美容师姓名
        $staff_phone = input('param.staff_phone');//美容师手机号
        $ord_num = input('param.ord_num');//订单号
        $store_id = input('param.store_id');//补贴门店
        $status = input('param.status');//状态 0.待入账 1.入账中 2.已入账 3.已退款  is_numeric
        $perPage = input('param.perPage');
        $page = input('param.page');
        $order_type = input('param.order_type');//订单类型  0全部 1新人专享 2秒杀 3超值组合 4i美套餐 5普通项目
        $store_type = input('param.store_type');//店铺类型 0全部 1品牌连锁店 2服务授权店	
        $staff_type = input('param.staff_type');//美容师类型 0全部 1品牌连锁店 2服务授权店
        $type = input('param.type');//1补贴收入 2补贴退款扣款
        
        if($id){
            $where['sfn.subsidy_setup_id'] = $id;
        }  else {
            if($type == 1){
                $where['sfn.subsidy_setup_id'] = ['<>',0];
            }elseif ($type == 2) {
                $where['sfn.pro_type'] = 23;
            }
            
        }
        if($start_time && $end_time){
            $where['sfn.add_time'] = ['between',[$start_time,$end_time]];
        }
        if($staff_name){
            $where['st.staff_name'] = ['like','%'.$staff_name.'%'];
        }
        if($staff_phone){
            $where['st.telephone'] = $staff_phone;
        }
        if($store_id){
            $where['y.store_id'] = $store_id;
        }
        if($ord_num){
            $where['o.ord_num'] = $ord_num;
        }
        if(is_numeric($status)){
            $where['sfn.status'] = $status;
        }
        if($start_time && $end_time){
            $where['sfn.add_time'] = ['between',[$start_time,$end_time]];
        }
        if($order_type == 1){//订单类型  0全部 1新人专享 2秒杀 3超值组合 4i美套餐 5普通项目
            $where['o.first_exemption'] = 2;
        }elseif ($order_type == 2) {
            $where['o.type'] = 5;
        }elseif ($order_type == 3) {
            $where['o.type'] = 2;
        }elseif ($order_type == 4) {
            $where['o.type'] = 1;
            $where['i.is_imeigroup'] = 1;
        }elseif ($order_type == 5) {
            $where['o.type'] = 1;
            $where['i.is_imeigroup'] = 2;
            $where['o.first_exemption'] = ['<>',2];
        }
        if($store_type){
            $where['s.type'] = $store_type;
        }
        if($staff_type){
            $where['st.type'] = $staff_type;
        }
        
        $perPage = isset($perPage) ? $perPage : 10;
        $page = isset($page) ? $page : 1;
        
        $where = isset($where)?$where:[];
        $list = Db::name('staff_flow_new')
                ->alias('sfn')
                ->join('yuyue y','y.id = sfn.order_id','left')
                ->join('order o','o.id = y.order_id','left')
                ->join('store s','s.id = y.store_id','left')
                ->join('staff st','st.id = sfn.staff_id','left')
                ->join('item i','i.id = y.item_id','left')
                ->field('sfn.id,sfn.subsidy_day_index,sfn.subsidy_money,sfn.add_time,sfn.status,sfn.type f_type,sfn.money,o.ord_num,s.store_name,s.type store_type,st.staff_name,st.type staff_type,st.telephone,o.first_exemption,o.type,i.is_imeigroup')
                ->where($where)
                ->order('id desc')
                ->paginate($perPage)
                ->each(function($item,$key){
                    $first_exemption = $item['first_exemption'];
                    $type = $item['type'];
                    $is_imeigroup = $item['is_imeigroup'];
                    if($first_exemption == 2){
                        $item['order_type'] = 1;//订单类型  0全部 1新人专享 2秒杀 3超值组合 4i美套餐 5普通项目
                    }elseif ($type == 5) {
                        $item['order_type'] = 2;
                    }elseif ($type == 2) {
                        $item['order_type'] = 3;
                    }elseif ($type == 1 && $is_imeigroup == 1) {
                        $item['order_type'] = 4;
                    }elseif ($type == 1 && $is_imeigroup == 2 && $first_exemption != 2) {
                        $item['order_type'] = 5;
                    }
                    return $item;
                });
//                print_r(Db::name('staff_flow_new')->getLastSql());
        return Utils::ajaxReturn(0, '查询成功', $list);
    }
    
    /*
     * 预警等级
     * author xfwed 
     * date 2021.07.12
     */

    public function warningLevelLog() {
        $rule = [
            'other_id' => 'require',
            'type' => 'require',
            'perPage' => 'integer|egt:1',
            'page' => 'integer|egt:1',
        ];
        $msg = [
            'other_id.require' => '其他id必须',
            'type.require' => '类型必须',
            'perPage.integer' => '每页数量为数字',
            'perPage.egt' => '每页数量最小为1',
            'page.integer' => '当前页数为数字',
            'page.egt' => '当前页数最小为1',
        ];
        $all = input('param.');
        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();
            return $this->ajaxReturn(1, $error, null);
        }
        $other_id = input('param.other_id');
        $type = input('param.type');//	1.用户 2.美容师 3.店铺	
        $perPage = isset($all['perPage']) ? $all['perPage'] : 20;
        $page = isset($all['page']) ? $all['page'] : 0;

        $relust = Db::name('warning_level_log')
                ->where('type', $type)
                ->where('other_id', $other_id)
                ->order('id desc')
                ->field('type,other_id', TRUE)
                ->paginate($perPage);
        if ($relust) {
            return $this->ajaxReturn(0, '查询成功', $relust);
        } else {
            return $this->ajaxReturn(3, '查询失败', null);
        }
    }
    
    /*
     * 添加回访记录
     * author xfwed 
     * date 2021.07.12
     */

    public function addWarningLevelNote() {
        $rule = [
            'waming_id' => 'require',
            'admin_name' => 'require',
            'note' => 'require',
        ];
        $msg = [
            'waming_id.require' => '预警id必须',
            'admin_name.require' => '后台管理员姓名必须',
            'note.require' => '回访记录必须',
        ];
        $all = input('param.');
        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();
            return $this->ajaxReturn(1, $error, null);
        }
        $waming_id = input('param.waming_id');	
        $admin_name = input('param.admin_name');	
        $note = input('param.note');	
       
        $data['waming_id'] = $waming_id;
        $data['admin_name'] = $admin_name;
        $data['note'] = $note;
        $data['add_time'] = date('Y-m-d H:i:s');
        $relust = Db::name('warning_level_note')->insert($data);
        Db::name('warning_level_log')->where('id',$waming_id)->update(['note'=>$note]);
        if ($relust) {
            return $this->ajaxReturn(0, '添加成功', $relust);
        } else {
            return $this->ajaxReturn(3, '添加失败', null);
        }
    }
    
    /*
     * 查看全部回访
     * author xfwed 
     * date 2021.07.12
     */

    public function warningLevelNote() {
        $rule = [
            'waming_id' => 'require',
        ];
        $msg = [
            'waming_id.require' => '预警id必须',
        ];
        $all = input('param.');
        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();
            return $this->ajaxReturn(1, $error, null);
        }
        $waming_id = input('param.waming_id');	

        $relust = Db::name('warning_level_note')
                ->where('waming_id', $waming_id)
                ->order('id desc')
                ->select();
        return $this->ajaxReturn(0, '查询成功', $relust);
    }
    
    /*
     * 美容师排行
     * author xfwed 
     * date 2021.07.20
     */

    public function staffRank() {
        $prov = input('param.prov');
        $city = input('param.city');
        $staffName = input('param.staffName');
        $staffPhone = input('param.staffPhone');
        $perPage = input('param.perPage');
        $page = input('param.page');
        $start_time = input('param.start_time');
        $end_time = input('param.end_time');
        //1入住时间 新->旧2入住时间 旧->新3收益 多->少4收益 少->多5绩效分 高->低6绩效分 低->高7接单量 多->少8接单量 少->多
        $orderType = input('param.orderType');
        $staff_type = input('param.staff_type');//美容师类型 0全部 1品牌连锁店 2服务授权店

        $status = isset($status) ? $status : 0;
        $perPage = isset($perPage) ? $perPage : 10;
        $page = isset($page) ? $page : 1;
        
        $order = 's.id desc';
        switch ($orderType) {
            case 1 :
                $order = 's.add_time desc, s.id desc';
                break;
            case 2 :
                $order = 's.add_time asc, s.id desc';
                break;
            case 3 :
                $order = 'f.money desc, s.id desc';
                break;
            case 4 :
                $order = 'f.money asc, s.id desc';
                break;
            case 5 :
                $order = 'c.score desc, s.id desc';
                break;
            case 6 :
                $order = 'c.score asc, s.id desc';
                break;
            case 7 :
                $order = 'y.serNum desc, s.id desc';
                break;
            case 8 :
                $order = 'y.serNum asc, s.id desc';
                break;
            default :
                $order = 's.id desc';
        }

        if ($prov) {
            $where['prov'] = $prov;
        }

        if ($city) {
            $where['city'] = $city;
        }

        if ($staffName) {
            $where['staff_name'] = ['like', '%' . $staffName . '%'];
        }
        if ($staffPhone) {
            $where['telephone'] = $staffPhone;
        }
        if($start_time && $end_time){
            $where1['add_time'] = ['between',[$start_time,$end_time]];
            $where2['staff_time'] = ['between',[$start_time,$end_time]];
        }
        if($staff_type){
            $where['s.type'] = $staff_type;
        }
        $where['staff_is_creator'] = 0;
        $where1 = isset($where1)?$where1:[];
        $where2 = isset($where2)?$where2:[];
        $staffFlowSql = Db::name('staff_flow_new')
                ->where('status','<>',3)
                ->where('type',1)
                ->where($where1)
                ->field('staff_id,SUM(money+subsidy_money) money')
                ->group('staff_id')
                ->buildSql();
        $serNumSql = Db::name('yuyue')
                ->where('status','in','4,7,8')
                ->where($where2)
                ->field('staff_id,count(id) serNum')
                ->group('staff_id')
                ->buildSql();
        $scoreSql = Db::name('staff_assess_score')
                ->where($where1)
                ->field('staff_id,sum(score) score')
                ->group('staff_id')
                ->buildSql();
        $staffList = Staff::alias('s')
                ->join('prov_city_area p','p.id = s.city','left')
                ->join([$staffFlowSql => 'f'],'f.staff_id=s.id','left')
                ->join([$serNumSql => 'y'],'y.staff_id=s.id','left')
                ->join([$scoreSql => 'c'],'c.staff_id=s.id','left')
                ->where($where)
                ->order($order)
                ->field('s.id,s.staff_name,s.telephone,s.add_time,s.type staff_type,p.name,IfNull(f.money,0) money,IfNull(y.serNum,0) serNum,IfNull(c.score,0) score')
                ->paginate($perPage);
//        print_r(Staff::getLastSql());
        return $this->ajaxReturn(0, '查询成功', $staffList);
    }
    
    /*
     * 设置美容师企业微信号
     * 日期 2021-08-03
     */

    public function addQyWechat() {
        $id = input('param.id'); //美容师id
        $qy_wechat = input('param.qy_wechat');//企业微信账号
        $row = Staff::where('id',$id)
                ->update(['qy_wechat'=>$qy_wechat]);
        if($row){
           return Utils::ajaxReturn(0, '设置成功', null);
        }  else {
           return Utils::ajaxReturn(3, '设置失败', null);
        }
    }

}
